package cn.mhome.easy.spring.thrift.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.mhome.easy.spring.thrift.client.support.ClientManager;
import cn.mhome.easy.spring.thrift.client.support.ConnectManager;

public class ThriftProxy implements InvocationHandler {
	
    protected static Logger logger = LoggerFactory.getLogger(ThriftProxy.class);

    public static final int TIMEOUT = 60000;
	
	private String serviceName;

	public ThriftProxy(String serviceName){
		this.serviceName = serviceName;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {


        //通过配置文件获取服务地址
        Object[] address = ConnectManager.getAddressMap(serviceName);
        if (address==null) {
            logger.debug("ThriftProxy address is null");
        	throw new RuntimeException(serviceName + " address is not found.");
        }else{
        	logger.info("serviceName:["+serviceName+"],serverIp:["+address[0]+"],serverPort:["+address[1]+"]");
        }
        TTransport transport =ConnectManager.getConnect((String)address[0],(Integer)address[1],TIMEOUT);


        //通过zookeeper获取服务地址
//        String serverNodeName = ZkCli.getServerName(serviceName);
//        if(serverNodeName==null){
//            logger.debug("ThriftProxy server node name is null");
//        }
//
//        ZkAddress zkAddress = ZkCli.getServer(serverNodeName);
//		if (zkAddress==null) {
//			logger.debug("ThriftProxy address is null");
//		}
//
//		TTransport transport = ConnectManager.getConnect(zkAddress.getIp(),zkAddress.getPort(),TIMEOUT);
		
		try{
			
			Object client = createClient(transport,serviceName);
			
			Method clientMethod = client.getClass().getMethod(method.getName(), method.getParameterTypes());
			
			return clientMethod.invoke(client, args);
		}finally{
			ConnectManager.close(transport);
		}
	}
	
	/**
	 * Object serviceName : 服务对象名称
	 * @return 服务对象的Client
	 */
	private Object createClient(TTransport transport,String serviceName) throws Exception{
		
		Object client = ClientManager.getClient(serviceName, transport);
		
		return client;
		
	}
	
}
